package com.zhiche.lisa.lspm.config;

import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.FromItem;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by qichao on 2018/7/13.
 */
public class CustomTenantSqlParser extends TenantSqlParser {

    @Override
    protected Expression builderExpression(Expression expression, Table table) {
        //生成字段名
        InExpression inExpression = new InExpression();
        inExpression.setLeftExpression(this.getAliasColumn(table));
        ExpressionList expressionList = new ExpressionList();
        String[] tenantArray = super.getTenantHandler().getTenantId().toString().split(",");
        List<String> tenantList = Arrays.asList(tenantArray);
        List<Expression> expressionList1 = new ArrayList<>();
        for(int i=0;i<tenantList.size();i++){
            String temp = StringUtils.strip(tenantList.get(i),"'");
            Expression expression1 = new StringValue(temp);
            expressionList1.add(expression1);
        }
        expressionList.setExpressions(expressionList1);
        inExpression.setRightItemsList(expressionList);
        //加入判断防止条件为空时生成 "and null" 导致查询结果为空
        if (expression == null) {
            return inExpression;
        } else {
            if (expression instanceof BinaryExpression) {
                BinaryExpression binaryExpression = (BinaryExpression) expression;
                if (binaryExpression.getLeftExpression() instanceof FromItem) {
                    processFromItem((FromItem) binaryExpression.getLeftExpression());
                }
                if (binaryExpression.getRightExpression() instanceof FromItem) {
                    processFromItem((FromItem) binaryExpression.getRightExpression());
                }
            }
            AndExpression andExpression = new AndExpression(inExpression, expression);
            return andExpression;
        }
    }
}
